<?php
namespace application\datatypes;

class Number extends DataType {
	public static $name = 'Number';
	public static $fields = array(array('columnType'=>'FLOAT(20,2)'));
	
	public static $displayParams = array(
		array(
			'label'=>'Decimal Places',
			'name'=>'decimals',
			'type'=>'text',
			'class'=>'thin'
		)
	);
	
	public static function validate($field, $data, $results) {
		if($field->cf_required && !$data[$field->cf_column]) {
			$results['errors'][] = '<b>'.$field->cf_display_name.'</b> is required.';
		}
		elseif(!is_numeric(preg_replace('/[^A-Za-z0-9]/', '', $data[$field->cf_column]))) {
			$results['errors'][] = $field->cf_display_name.' must be numbers only.';
		}
		elseif($value = $data[$field->cf_column]) {
			$results['db_fields'][$field->cf_column] = preg_replace('/[^A-Za-z0-9\.]/', '', $value);	
		}
		
		return $results;
	}
	
	public static function display($formElements) {
		?>
		
		<fieldset class="single-field">
			<header><?=$formElements['display']?></header>
			<section class="inner">
			<?php if($description = $formElements['description']) : ?>
				<p class="form-description"><?=$description?></p>
			<?php endif;?>
			<?=$formElements['elements']['element']?>
			</section>
		</fieldset>
		<?php
	}
	
	public static function build($field, $data) {
		$value = number_format((double)str_replace(',', '', $data[$field->cf_column]), 2);
		$formElements = array('description'=>$field->cf_description, 'column'=>$field->cf_column, 'display'=>$field->cf_display_name, 'data_type'=>$field->cf_data_type,'elements'=>array(
						'element'=>
							sprintf('<input type="text" value="%1$s" class="short-text" name="%2$s" id="%2$s"/>', $value, $field->cf_column)
						
		));
		return $formElements;
	
	}
	
	
	
	public static function prepareData($field, $data, $params) {
		if($params['decimals']) $params['decimals'] = 2;
		return number_format($data[$field->cf_column], $params['decimals']);
	}
	
}
?>